package com.nanbei.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @ClassDescription: CAS 中防止ABA问题
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/10/9 11:31
 */
public class ABADemo {
    public static void main(String[] args) {
        //定义一个带版本号的原子类 初始值为0，初始版本号为0
        AtomicStampedReference<Integer> integerAtomicStampedReference = new AtomicStampedReference<>(0, 0);

        new Thread(()->{
            // 1.获取初始原子类的版本号
            int stamp = integerAtomicStampedReference.getStamp();
            try { TimeUnit.MILLISECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }

            // 2. t1线程修改数值，并把版本号+1
            integerAtomicStampedReference.compareAndSet(0,10,stamp,stamp+1);


            // 3. 一段时间后 t1线程又将值改为原来的值 版本号+1
            integerAtomicStampedReference.compareAndSet(10,0,
                    integerAtomicStampedReference.getStamp(),integerAtomicStampedReference.getStamp()+1);

        },"t1").start();

        new Thread(()->{
            // 1.获取初始原子类的版本号
            int stamp = integerAtomicStampedReference.getStamp();
            try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); }

            System.out.println("t2开始更新前的版本号为："+integerAtomicStampedReference.getStamp());
            boolean b = integerAtomicStampedReference.compareAndSet(0, 999, stamp, stamp + 1);
            System.out.println("t2线程更新情况："+b);

        },"t2").start();

    }
}
